const mysql = require("mysql2/promise");
const config = require("./config/base");

// 数据库初始化函数
async function initializeDatabase() {
  let connection;
  try {
    console.log("开始初始化数据库...");
    connection = await mysql.createConnection({
      host: config.db.host,
      user: config.db.user,
      password: config.db.password,
    });

    console.log("创建数据库...");
    await connection.query(
      `CREATE DATABASE IF NOT EXISTS ${config.db.database}`
    );

    console.log("使用数据库...");
    await connection.query(`USE ${config.db.database}`);

    console.log("创建用户表...");
    await connection.query(`
        CREATE TABLE IF NOT EXISTS users (
          id INT PRIMARY KEY AUTO_INCREMENT,
          username VARCHAR(50) NOT NULL UNIQUE,
          password VARCHAR(255) NOT NULL,
          nickname VARCHAR(100) DEFAULT NULL,
          avatar VARCHAR(255),
          phone VARCHAR(20),
          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )
    `);

    console.log("创建聊天历史表...");
    await connection.query(`
      CREATE TABLE IF NOT EXISTS chat_history (
        id INT PRIMARY KEY AUTO_INCREMENT,
        user_id INT NOT NULL,
        title VARCHAR(100),
        question TEXT NOT NULL,
        answer TEXT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES users(id)
      )
    `);

    console.log("创建反馈表...");
    await connection.query(`
        CREATE TABLE IF NOT EXISTS feedback (
          id INT PRIMARY KEY AUTO_INCREMENT,
          user_id INT NOT NULL,
          content TEXT NOT NULL,
          status ENUM('pending', 'processing', 'resolved') DEFAULT 'pending',
          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          FOREIGN KEY (user_id) REFERENCES users(id)
        )
    `);

    console.log("数据库初始化完成");
  } catch (error) {
    console.error("数据库初始化失败:", error);
    throw error;
  } finally {
    if (connection) {
      await connection.end();
      console.log("数据库连接已关闭");
    }
  }
}

module.exports = initializeDatabase;
